<template>
  <div class="hamd-survey">
    <div class="header">
      <h1>{{ surveyConfig.title }}</h1>
      <p class="subtitle">{{ surveyConfig.subtitle }}</p>
      <div class="header-actions">
        <button @click="goToHome" class="home-btn">
          <span class="home-icon">🏠</span> {{ surveyConfig.buttons.home }}
        </button>
        <button @click="showSettings = true" class="settings-btn">
          <span class="settings-icon">⚙️</span> {{ surveyConfig.buttons.settings }}
        </button>
      </div>
    </div>

    <!-- 设置页面 -->
    <div class="settings-modal" v-if="showSettings">
      <div class="settings-content">
        <div class="settings-header">
          <h2>{{ surveyConfig.settings.title }}</h2>
          <button @click="closeSettings" class="close-btn">×</button>
        </div>

        <div class="settings-form">
          <div class="form-group">
            <label>问答编号：<span class="required">*</span></label>
            <input type="text" v-model="recorderInfo.surveyId" placeholder="请输入问答编号（用于区分不同组的问卷）" maxlength="20">
            <p class="field-hint">编号用于区分不同组的问卷，建议使用如：GROUP001、BATCH_A等格式</p>
          </div>
          <div class="form-group">
            <label>记录人姓名：<span class="required">*</span></label>
            <input type="text" v-model="recorderInfo.name" placeholder="请输入记录人姓名">
          </div>
          <div class="form-group">
            <label>记录人职务/身份：<span class="required">*</span></label>
            <input type="text" v-model="recorderInfo.position" placeholder="请输入职务或身份（如：医生、护士、研究员等）">
          </div>
          <div class="form-group">
            <label>所属机构：</label>
            <input type="text" v-model="recorderInfo.institution" placeholder="请输入所属医院或机构名称">
          </div>
          <div class="form-group">
            <label>联系方式：</label>
            <input type="text" v-model="recorderInfo.contact" placeholder="请输入联系电话或邮箱">
          </div>
          <div class="form-group">
            <label>默认备注：</label>
            <textarea v-model="recorderInfo.defaultRemarks" placeholder="请输入默认备注信息（可选）" rows="3"></textarea>
          </div>
        </div>

        <div class="settings-actions">
          <button @click="saveRecorderInfo" class="save-settings-btn">保存设置</button>
          <button @click="closeSettings" class="cancel-btn">取消</button>
        </div>
      </div>
    </div>

    <!-- 记录人信息显示 -->
    <div class="recorder-info-display" v-if="recorderInfo.name && !showSettings && !showResult && !showExport">
      <div class="recorder-card">
        <div class="recorder-main-info">
          <h3>问答编号：{{ recorderInfo.surveyId }}</h3>
          <p>记录人：{{ recorderInfo.name }} | {{ recorderInfo.position }}</p>
          <p v-if="recorderInfo.institution">{{ recorderInfo.institution }}</p>
        </div>
        <div class="recorder-actions">
          <button @click="showSettings = true" class="edit-recorder-btn">编辑</button>
          <button @click="showExportDialog" class="export-btn">{{ surveyConfig.buttons.export }}</button>
        </div>
      </div>
    </div>

    <!-- 导出数据模态框 -->
    <div class="export-modal" v-if="showExport">
      <div class="export-content">
        <div class="export-header">
          <h2>{{ surveyConfig.export.title }}</h2>
          <button @click="closeExport" class="close-btn">×</button>
        </div>

        <div class="export-form">
          <div class="export-info">
            <p><strong>当前问答编号：</strong>{{ recorderInfo.surveyId }}</p>
            <p><strong>导出说明：</strong>将从服务器打包当前编号的所有问卷数据</p>
          </div>

          <div class="form-group">
            <label>导出密码：<span class="required">*</span></label>
            <input type="password" v-model="exportPassword" placeholder="请输入导出密码" @keyup.enter="exportData">
            <p class="field-hint">请联系管理员获取导出密码</p>
          </div>

          <div class="export-options">
            <div class="form-group">
              <label>
                <input type="checkbox" v-model="exportOptions.includeRawData">
                包含原始评估数据
              </label>
            </div>
            <div class="form-group">
              <label>
                <input type="checkbox" v-model="exportOptions.includeStatistics">
                包含统计分析
              </label>
            </div>
          </div>
        </div>

        <div class="export-actions">
          <button @click="exportData" class="export-confirm-btn" :disabled="!exportPassword">
            <span v-if="!isExporting">导出压缩包</span>
            <span v-else>导出中...</span>
          </button>
          <button @click="closeExport" class="cancel-btn">取消</button>
        </div>
      </div>
    </div>

    <div class="survey-form" v-if="!showResult && !showSettings && !showExport">
      <!-- 被评估人基本信息 -->
      <div class="section">
        <h2>{{ surveyConfig.sections.basicInfo.title }}</h2>
        <div class="form-group" v-for="field in surveyConfig.sections.basicInfo.fields" :key="field.name">
          <label>{{ field.label }}：</label>
          <input 
            v-if="field.type === 'text' || field.type === 'number' || field.type === 'tel' || field.type === 'datetime-local'"
            :type="field.type" 
            v-model="formData[field.name]" 
            :placeholder="field.placeholder"
            :min="field.min"
            :max="field.max"
            :step="field.step"
            :rows="field.rows"
          >
          <textarea 
            v-else-if="field.type === 'textarea'"
            v-model="formData[field.name]" 
            :placeholder="field.placeholder"
            :rows="field.rows"
          ></textarea>
          <div v-else-if="field.type === 'radio'" class="radio-group">
            <label v-for="option in field.options" :key="option.value">
              <input type="radio" v-model="formData[field.name]" :value="option.value"> {{ option.label }}
            </label>
          </div>
        </div>
      </div>

      <!-- 问卷项目 -->
      <div class="section">
        <h2>{{ surveyConfig.sections.assessment.title }}</h2>

        <div class="question-item" v-for="(question, index) in surveyConfig.sections.assessment.questions" :key="question.id">
          <h3>{{ index + 1 }}. {{ question.title }}</h3>
          <p class="question-desc">{{ question.description }}</p>
          
          <!-- 单选题 -->
          <div v-if="question.type === 'radio'" class="radio-group">
            <label v-for="option in question.options" :key="option.value" class="radio-option">
              <input type="radio" v-model="formData[question.field]" :value="option.value"> 
              <span class="radio-text">{{ option.label }}</span>
            </label>
          </div>
          
          <!-- 提示信息 -->
          <p v-if="question.hint" class="hint">{{ question.hint }}</p>
        </div>
      </div>

      <div class="submit-section">
        <button @click="calculateResult" class="submit-btn" :disabled="!isFormValid">{{ surveyConfig.buttons.submit }}</button>
      </div>
    </div>

    <!-- 结果展示 -->
    <div class="result-section" v-if="showResult">
      <h2>{{ surveyConfig.result.title }}</h2>
      <div class="result-card">
        <div class="result-summary">
          <h3>{{ result.diagnosis }}</h3>
          <p class="score">{{ surveyConfig.result.totalScore }}：{{ result.totalScore }}/{{ result.maxTotalScore }}</p>
          <p class="severity" :class="result.riskLevel">{{ result.severity }}</p>
          <div v-if="result.suicideRisk" class="suicide-warning">
            ⚠️ 检测到自杀风险，请立即寻求专业帮助！
          </div>
        </div>

        <div class="result-details">
          <h4>{{ surveyConfig.result.details }}：</h4>
          <div class="details-grid">
            <div v-for="(item, index) in result.details" :key="index" class="detail-item" :class="{ critical: item.critical }">
              <span class="detail-name">{{ item.name }}</span>
              <span class="detail-score">{{ item.score }}/{{ item.maxScore }}</span>
              <span class="detail-result">{{ item.result }}</span>
              <span v-if="item.critical" class="critical-mark">⚠️</span>
            </div>
          </div>
        </div>

        <div class="result-recommendations" v-if="result.recommendations && result.recommendations.length > 0">
          <h4>专业建议：</h4>
          <div v-for="(rec, index) in result.recommendations" :key="index" class="recommendation" :class="rec.type">
            <h5>{{ rec.title }}</h5>
            <p>{{ rec.content }}</p>
          </div>
        </div>

        <div class="result-explanation">
          <h4>{{ surveyConfig.result.explanation.title }}：</h4>
          <ul>
            <li v-for="item in surveyConfig.result.explanation.items" :key="item">{{ item }}</li>
          </ul>
        </div>

        <div class="action-buttons">
          <button @click="saveToBackendOnly" class="save-btn" :disabled="isSaving">
            <span v-if="!isSaving">{{ surveyConfig.buttons.save }}</span>
            <span v-else>{{ surveyConfig.buttons.saving }}</span>
          </button>
          <button @click="resetForm" class="reset-btn">{{ surveyConfig.buttons.reset }}</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { hamdConfig } from '@/config/hamdConfig.js';
import { calculateHAMDAssessment, generateHAMDReport } from '@/config/hamdLogic.js';

export default {
  name: 'HAMDSurvey',
  mounted() {
    // 自动设置当前时间
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    this.formData.recordTime = `${year}-${month}-${day}T${hours}:${minutes}`;

    // 加载记录人信息
    this.loadRecorderInfo();
  },
  data() {
    return {
      surveyConfig: hamdConfig,
      showResult: false,
      showSettings: false,
      showExport: false,
      isExporting: false,
      isSaving: false,
      exportPassword: '',
      // 记录人信息（设置）
      recorderInfo: {
        surveyId: '',
        name: '',
        position: '',
        institution: '',
        contact: '',
        defaultRemarks: ''
      },
      // 导出选项
      exportOptions: hamdConfig.exportOptions,
      // 问卷表单数据
      formData: {
        // 被评估人信息
        patientName: '',
        age: null,
        gender: '',
        phone: '',
        // 当前评估的记录时间和备注
        recordTime: '',
        remarks: '',
        // HAMD评估项目
        depression: null,
        guilt: null,
        suicide: null,
        insomnia_early: null,
        insomnia_middle: null,
        insomnia_late: null,
        work_interests: null,
        retardation: null,
        agitation: null,
        anxiety_psychic: null,
        anxiety_somatic: null,
        somatic_gastrointestinal: null,
        somatic_general: null,
        genital_symptoms: null,
        hypochondriasis: null,
        loss_of_weight: null,
        insight: null
      },
      result: {
        totalScore: 0,
        maxTotalScore: 52,
        diagnosis: '',
        severity: '',
        riskLevel: 'low',
        suicideRisk: false,
        details: [],
        recommendations: []
      }
    }
  },
  computed: {
    isFormValid() {
      // 检查记录人信息
      if (!this.recorderInfo.surveyId || !this.recorderInfo.name || !this.recorderInfo.position) {
        return false;
      }
      
      // 个人信息字段已改为选填，不再进行必填验证
      
      // 检查所有HAMD评估项目是否已填写
      const requiredFields = [
        'depression', 'guilt', 'suicide', 'insomnia_early', 'insomnia_middle', 'insomnia_late',
        'work_interests', 'retardation', 'agitation', 'anxiety_psychic', 'anxiety_somatic',
        'somatic_gastrointestinal', 'somatic_general', 'genital_symptoms', 'hypochondriasis',
        'loss_of_weight', 'insight'
      ];
      
      return requiredFields.every(field => {
        const value = this.formData[field];
        return value !== undefined && value !== null && value !== '';
      });
    }
  },
  methods: {
    // 导航方法
    goToHome() {
      this.$router.push('/');
    },

    // 设置相关方法
    saveRecorderInfo() {
      // 验证必填字段
      if (!this.recorderInfo.surveyId || !this.recorderInfo.name || !this.recorderInfo.position) {
        alert('请填写所有必填信息（问答编号、记录人姓名、职务/身份）！');
        return;
      }

      // 保存记录人信息到本地存储
      localStorage.setItem('hamdRecorderInfo', JSON.stringify(this.recorderInfo));
      // 设置默认备注
      if (this.recorderInfo.defaultRemarks && !this.formData.remarks) {
        this.formData.remarks = this.recorderInfo.defaultRemarks;
      }
      this.showSettings = false;
      alert('记录人信息已保存！');
    },

    closeSettings() {
      this.showSettings = false;
    },

    loadRecorderInfo() {
      // 从本地存储加载记录人信息
      const saved = localStorage.getItem('hamdRecorderInfo');
      if (saved) {
        this.recorderInfo = JSON.parse(saved);
        // 设置默认备注
        if (this.recorderInfo.defaultRemarks && !this.formData.remarks) {
          this.formData.remarks = this.recorderInfo.defaultRemarks;
        }
      }
    },

    // 导出相关方法
    showExportDialog() {
      this.showExport = true;
      this.exportPassword = '';
    },

    closeExport() {
      this.showExport = false;
      this.exportPassword = '';
      this.isExporting = false;
    },

    async exportData() {
      this.isExporting = true;

      try {
        // 发送导出请求到服务器
        const response = await fetch(`${window.location.protocol}//${window.location.hostname}:13000/api/export-hamd-survey`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            surveyId: this.recorderInfo.surveyId,
            password: this.exportPassword,
            exportOptions: this.exportOptions
          })
        });

        if (response.status === 401) {
          alert('密码错误，请重新输入！');
          return;
        }

        if (!response.ok) {
          throw new Error('导出请求失败');
        }

        // 获取服务器返回的压缩包
        const blob = await response.blob();

        if (blob.size === 0) {
          alert('当前问答编号下没有问卷数据！');
          return;
        }

        // 下载服务器生成的压缩包
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `HAMD问卷数据_${this.recorderInfo.surveyId}_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.zip`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);

        alert('数据导出成功！');
        this.closeExport();
      } catch (error) {
        console.error('导出失败:', error);
        alert('导出失败，请检查网络连接或联系管理员！');
      } finally {
        this.isExporting = false;
      }
    },

    calculateResult() {
      // 使用HAMD评估逻辑
      this.result = calculateHAMDAssessment(this.formData);
      this.showResult = true;
    },

    async saveToBackendOnly() {
      this.isSaving = true;

      try {
        // 1. 保存问卷数据到后台
        await this.saveToBackend();

        // 2. 生成评估报告内容
        const surveyData = {
          ...this.formData,
          ...this.result
        };
        const content = generateHAMDReport(surveyData, this.recorderInfo);

        // 3. 保存评估报告到@data/文件夹
        await this.saveFileToDataFolder(content);

        alert('✅ 数据已成功保存到后台！\n\n📁 问卷数据：survey_data/\n📄 评估报告：@data/');

      } catch (error) {
        console.error('保存到后台失败:', error);
        alert('❌ 保存失败，请检查网络连接或联系管理员！\n\n错误信息：' + error.message);
      } finally {
        this.isSaving = false;
      }
    },

    async saveFileToDataFolder(content) {
      // 通过API保存文件到@data/文件夹
      const filename = `HAMD抑郁评估结果_${this.recorderInfo.surveyId}_${this.formData.patientName}_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.txt`;

      const response = await fetch(`${window.location.protocol}//${window.location.hostname}:13000/api/save-file`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          filename: filename,
          content: content,
          surveyId: this.recorderInfo.surveyId
        })
      });

      if (!response.ok) {
        throw new Error('保存文件失败');
      }

      const result = await response.json();
      console.log('文件已保存到:', result.filepath);
    },

    async saveToBackend() {
      // 构建要保存的数据
      const surveyData = {
        surveyType: 'HAMD',
        surveyId: this.recorderInfo.surveyId,
        recordTime: this.formData.recordTime,
        recorderName: this.recorderInfo.name,
        recorderPosition: this.recorderInfo.position,
        recorderInstitution: this.recorderInfo.institution,
        recorderContact: this.recorderInfo.contact,
        // 被评估人信息
        patientName: this.formData.patientName || "未填写",
        age: this.formData.age || 0,
        gender: this.formData.gender,
        phone: this.formData.phone,
        remarks: this.formData.remarks,
        // HAMD评估数据
        depression: this.formData.depression,
        guilt: this.formData.guilt,
        suicide: this.formData.suicide,
        insomnia_early: this.formData.insomnia_early,
        insomnia_middle: this.formData.insomnia_middle,
        insomnia_late: this.formData.insomnia_late,
        work_interests: this.formData.work_interests,
        retardation: this.formData.retardation,
        agitation: this.formData.agitation,
        anxiety_psychic: this.formData.anxiety_psychic,
        anxiety_somatic: this.formData.anxiety_somatic,
        somatic_gastrointestinal: this.formData.somatic_gastrointestinal,
        somatic_general: this.formData.somatic_general,
        genital_symptoms: this.formData.genital_symptoms,
        hypochondriasis: this.formData.hypochondriasis,
        loss_of_weight: this.formData.loss_of_weight,
        insight: this.formData.insight,
        // 评估结果
        totalScore: this.result.totalScore,
        maxTotalScore: this.result.maxTotalScore,
        diagnosis: this.result.diagnosis,
        severity: this.result.severity,
        riskLevel: this.result.riskLevel,
        suicideRisk: this.result.suicideRisk,
        // 时间戳
        createdAt: new Date().toISOString()
      };

      try {
        // 发送到后台API保存到工程文件夹
        const response = await fetch(`${window.location.protocol}//${window.location.hostname}:13000/api/save-hamd-survey`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(surveyData)
        });

        if (response.ok) {
          console.log('HAMD问卷数据已保存到服务器文件夹');
        } else {
          throw new Error('保存失败');
        }
      } catch (error) {
        console.error('保存到服务器失败，使用本地存储备份:', error);
        // 如果服务器保存失败，使用本地存储作为备份
        const existingSurveys = JSON.parse(localStorage.getItem('surveyData') || '[]');
        existingSurveys.push(surveyData);
        localStorage.setItem('surveyData', JSON.stringify(existingSurveys));
      }
    },

    resetForm() {
      // 重置表单数据，但保留记录人信息
      this.formData = {
        // 被评估人信息
        patientName: '',
        age: null,
        gender: '',
        phone: '',
        // 当前评估的记录时间和备注
        recordTime: '',
        remarks: this.recorderInfo.defaultRemarks || '',
        // HAMD评估项目
        depression: null,
        guilt: null,
        suicide: null,
        insomnia_early: null,
        insomnia_middle: null,
        insomnia_late: null,
        work_interests: null,
        retardation: null,
        agitation: null,
        anxiety_psychic: null,
        anxiety_somatic: null,
        somatic_gastrointestinal: null,
        somatic_general: null,
        genital_symptoms: null,
        hypochondriasis: null,
        loss_of_weight: null,
        insight: null
      };

      // 重新设置当前时间
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      this.formData.recordTime = `${year}-${month}-${day}T${hours}:${minutes}`;

      this.result = {
        totalScore: 0,
        maxTotalScore: 52,
        diagnosis: '',
        severity: '',
        riskLevel: 'low',
        suicideRisk: false,
        details: [],
        recommendations: []
      };
      this.showResult = false;
    }
  }
}
</script>

<style scoped>
.hamd-survey {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Microsoft YaHei', Arial, sans-serif;
}

.header {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 10px;
}

.header h1 {
  margin: 0 0 10px 0;
  font-size: 28px;
}

.subtitle {
  margin: 0 0 15px 0;
  opacity: 0.9;
  font-size: 16px;
}

.header-actions {
  margin-top: 15px;
}

.home-btn, .settings-btn {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: 2px solid rgba(255, 255, 255, 0.3);
  padding: 10px 20px;
  border-radius: 25px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  margin-right: 10px;
}

.home-btn:hover, .settings-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
  transform: translateY(-1px);
}

.home-icon, .settings-icon {
  font-size: 16px;
}

/* 设置模态框样式 */
.settings-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.settings-content {
  background: white;
  border-radius: 10px;
  padding: 30px;
  max-width: 500px;
  width: 90%;
  max-height: 80vh;
  overflow-y: auto;
}

.settings-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
}

.settings-header h2 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: #666;
}

/* 记录人信息显示样式 */
.recorder-info-display {
  margin-bottom: 30px;
}

.recorder-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  border-radius: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.recorder-main-info h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
}

.recorder-main-info p {
  margin: 4px 0;
  opacity: 0.9;
}

.recorder-actions {
  display: flex;
  gap: 10px;
}

.edit-recorder-btn, .export-btn {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: 2px solid rgba(255, 255, 255, 0.3);
  padding: 8px 16px;
  border-radius: 20px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.edit-recorder-btn:hover, .export-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
}

/* 导出模态框样式 */
.export-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.export-content {
  background: white;
  border-radius: 10px;
  padding: 30px;
  max-width: 500px;
  width: 90%;
  max-height: 80vh;
  overflow-y: auto;
}

.export-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
}

.export-info {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.export-info p {
  margin: 5px 0;
}

.export-options {
  margin: 20px 0;
}

.export-options .form-group {
  margin: 10px 0;
}

.export-options label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.export-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  margin-top: 20px;
}

.export-confirm-btn {
  background: #667eea;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
}

.export-confirm-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.cancel-btn {
  background: #6c757d;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
}

.section {
  background: white;
  border-radius: 10px;
  padding: 25px;
  margin-bottom: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  border: 1px solid #e1e8ed;
}

.section h2 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 22px;
  border-bottom: 2px solid #667eea;
  padding-bottom: 10px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #555;
}

.required {
  color: #e74c3c;
}

.form-group input, .form-group textarea {
  width: 100%;
  padding: 12px;
  border: 2px solid #e1e8ed;
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.3s;
  box-sizing: border-box;
}

.form-group input:focus, .form-group textarea:focus {
  outline: none;
  border-color: #667eea;
}

.field-hint {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
  margin-bottom: 0;
}

.settings-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  margin-top: 20px;
}

.save-settings-btn {
  background: #667eea;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
}

.question-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  border-left: 4px solid #667eea;
}

.question-item h3 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 18px;
}

.question-desc {
  color: #666;
  margin-bottom: 15px;
  line-height: 1.5;
}

.radio-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.radio-option {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  padding: 10px;
  border: 2px solid #e1e8ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.radio-option:hover {
  border-color: #667eea;
  background: #f0f4ff;
}

.radio-option input[type="radio"] {
  margin: 0;
  width: auto;
}

.radio-text {
  flex: 1;
  line-height: 1.4;
}

.submit-section {
  text-align: center;
  margin-top: 30px;
}

.submit-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 15px 40px;
  border-radius: 25px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.submit-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.submit-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 结果展示样式 */
.result-section {
  margin-top: 30px;
}

.result-section h2 {
  text-align: center;
  color: #333;
  margin-bottom: 20px;
}

.result-card {
  background: white;
  border-radius: 10px;
  padding: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  border: 1px solid #e1e8ed;
}

.result-summary {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 10px;
}

.result-summary h3 {
  margin: 0 0 10px 0;
  font-size: 24px;
}

.score {
  font-size: 20px;
  font-weight: bold;
  margin: 10px 0;
}

.severity {
  font-size: 16px;
  margin: 10px 0;
  padding: 8px 16px;
  border-radius: 20px;
  display: inline-block;
}

.severity.low {
  background: rgba(40, 167, 69, 0.2);
  color: #28a745;
}

.severity.medium {
  background: rgba(255, 193, 7, 0.2);
  color: #ffc107;
}

.severity.high {
  background: rgba(255, 87, 34, 0.2);
  color: #ff5722;
}

.severity.critical {
  background: rgba(244, 67, 54, 0.2);
  color: #f44336;
}

.suicide-warning {
  background: #f44336;
  color: white;
  padding: 15px;
  border-radius: 8px;
  margin-top: 15px;
  font-weight: bold;
  text-align: center;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.7; }
  100% { opacity: 1; }
}

.result-details {
  margin-bottom: 30px;
}

.result-details h4 {
  margin: 0 0 15px 0;
  color: #333;
}

.details-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 10px;
}

.detail-item {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr auto;
  gap: 10px;
  align-items: center;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 5px;
  border-left: 3px solid #667eea;
}

.detail-item.critical {
  border-left-color: #f44336;
  background: #ffebee;
}

.detail-name {
  font-weight: 500;
}

.detail-score {
  text-align: center;
  font-weight: bold;
}

.detail-result {
  text-align: center;
  color: #666;
}

.critical-mark {
  color: #f44336;
  font-size: 16px;
}

.result-recommendations {
  margin-bottom: 30px;
}

.result-recommendations h4 {
  margin: 0 0 15px 0;
  color: #333;
}

.recommendation {
  margin-bottom: 15px;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #667eea;
}

.recommendation.success {
  background: #d4edda;
  border-left-color: #28a745;
}

.recommendation.warning {
  background: #fff3cd;
  border-left-color: #ffc107;
}

.recommendation.danger {
  background: #f8d7da;
  border-left-color: #dc3545;
}

.recommendation.critical {
  background: #f5c6cb;
  border-left-color: #f44336;
}

.recommendation.info {
  background: #d1ecf1;
  border-left-color: #17a2b8;
}

.recommendation h5 {
  margin: 0 0 8px 0;
  font-size: 16px;
}

.recommendation p {
  margin: 0;
  line-height: 1.5;
}

.result-explanation {
  margin-bottom: 30px;
}

.result-explanation h4 {
  margin: 0 0 15px 0;
  color: #333;
}

.result-explanation ul {
  margin: 0;
  padding-left: 20px;
}

.result-explanation li {
  margin-bottom: 8px;
  line-height: 1.5;
}

.action-buttons {
  display: flex;
  gap: 15px;
  justify-content: center;
  flex-wrap: wrap;
}

.save-btn, .reset-btn {
  padding: 12px 30px;
  border: none;
  border-radius: 25px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.save-btn {
  background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
  color: white;
  box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
}

.save-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(40, 167, 69, 0.4);
}

.save-btn:disabled {
  background: #6c757d;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.reset-btn {
  background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
  color: white;
  box-shadow: 0 4px 15px rgba(108, 117, 125, 0.3);
}

.reset-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(108, 117, 125, 0.4);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .hamd-survey {
    padding: 10px;
  }
  
  .header {
    padding: 15px;
  }
  
  .header h1 {
    font-size: 24px;
  }
  
  .header-actions {
    flex-direction: column;
    gap: 10px;
  }
  
  .home-btn, .settings-btn {
    margin-right: 0;
  }
  
  .section {
    padding: 20px;
  }
  
  .recorder-card {
    flex-direction: column;
    text-align: center;
  }
  
  .recorder-actions {
    justify-content: center;
  }
  
  .details-grid {
    grid-template-columns: 1fr;
  }
  
  .detail-item {
    grid-template-columns: 1fr;
    text-align: center;
  }
  
  .action-buttons {
    flex-direction: column;
    align-items: center;
  }
  
  .save-btn, .reset-btn {
    width: 200px;
  }
}
</style>